<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="custom-image" content="https://totemlife.cn/apps/public/trial-home-cover.jpg">
    <title>受试者详情</title>
    <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col">
                <h2>
                    <a href="/apps/trial" class="text-decoration-none">临床研究支持</a>
                    <i class="bi bi-chevron-right"></i>
                    <a href="/apps/trial/admin/trials/{{trial.id}}/dashboard" class="text-decoration-none">试验看板</a>
                    <i class="bi bi-chevron-right"></i>
                    受试者详情
                </h2>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">基本信息</h5>
                <div class="row">
                    <div class="col-md-3">
                        <p class="mb-1">
                            <strong>姓名：</strong>{{subject.real_name}}
                            <small class="text-muted">(UID: {{subject.user_id}})</small>
                        </p>
                        <p class="mb-1"><strong>手机：</strong>{{subject.phone}}</p>
                        <p class="mb-1">
                            <strong>状态：</strong>
                            <span class="badge {{#if (eq subject.status 0)}}bg-secondary
                                {{else if (eq subject.status 1)}}bg-info
                                {{else if (eq subject.status 2)}}bg-primary
                                {{else if (eq subject.status 3)}}bg-success
                                {{else if (eq subject.status 4)}}bg-danger
                                {{else}}bg-dark{{/if}}">
                                {{subject.status_text}}
                            </span>
                        </p>
                    </div>
                    <div class="col-md-3">
                        <p class="mb-1"><strong>创建时间：</strong>{{formatDate subject.created_at "YYYY-MM-DD HH:mm:ss"}}</p>
                        <p class="mb-1"><strong>报名时间：</strong>{{formatDate subject.apply_time "YYYY-MM-DD HH:mm:ss"}}</p>
                        <p class="mb-1"><strong>入组时间：</strong>{{formatDate subject.entry_time "YYYY-MM-DD HH:mm:ss"}}</p>
                        <p class="mb-1"><strong>分组时间：</strong>{{formatDate subject.group_time "YYYY-MM-DD HH:mm:ss"}}</p>
                        <p class="mb-1"><strong>开始日期：</strong>{{formatDate subject.start_date "YYYY-MM-DD"}}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加管理动作卡片 -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">管理动作</h5>
                <div class="d-flex flex-wrap gap-2">
                    {{#if (eq subject.status 1)}}
                    <button type="button" class="btn btn-danger"
                            data-bs-toggle="modal"
                            data-bs-target="#cancelModal">
                        <i class="fas fa-times-circle me-1"></i>取消报名
                    </button>
                    {{/if}}

                    {{#if (eq subject.status 2)}}
                    <button type="button" class="btn btn-primary"
                            data-bs-toggle="modal"
                            data-bs-target="#groupModal"
                            data-subject-id="{{subject.id}}"
                            data-subject-name="{{subject.real_name}}">
                        <i class="fas fa-users me-1"></i>设置分组
                    </button>
                    <button type="button" class="btn btn-danger"
                            data-bs-toggle="modal"
                            data-bs-target="#cancelModal">
                        <i class="fas fa-times-circle me-1"></i>取消报名
                    </button>
                    {{/if}}

                    {{#if (gte subject.status 3)}}
                    <button type="button" class="btn btn-danger"
                            data-bs-toggle="modal"
                            data-bs-target="#exitModal">
                        <i class="fas fa-sign-out-alt me-1"></i>退出试验
                    </button>

                    <button type="button" class="btn btn-success"
                            data-bs-toggle="modal"
                            data-bs-target="#finishModal">
                        <i class="fas fa-check-circle me-1"></i>完成试验
                    </button>

                    <a href="/apps/trial/diary/list/{{trial.id}}?subject_id={{subject.id}}"
                       class="btn btn-info"
                       target="_blank">
                        <i class="fas fa-book me-1"></i>查看日记
                    </a>

                    <button class="btn btn-primary" id="viewFollowupBtn" data-subject-id="{{subject.id}}" data-trial-id="{{trial.id}}">
                        <i class="fas fa-clipboard-check me-1"></i>随访报告
                    </button>

                    {{/if}}

                    <button type="button" class="btn btn-secondary"
                            data-bs-toggle="modal"
                            data-bs-target="#profileModal">
                        <i class="fas fa-comment me-1"></i>备注档案
                    </button>
                </div>
            </div>
        </div>

        {{#if subject.apply_info}}
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">报名信息</h5>
                <div class="row g-3">
                    {{#with (parseJson subject.apply_info)}}
                    <div class="col-md-4">
                        <p class="mb-1"><strong>受试者姓名：</strong>{{subject_name}}</p>
                        <p class="mb-1"><strong>性别：</strong>{{#if (eq gender "1")}}男{{else}}女{{/if}}</p>
                        <p class="mb-1"><strong>出生日期：</strong>{{birth_date}}</p>
                        <p class="mb-1"><strong>年龄：</strong>{{age}}</p>
                    </div>
                    <div class="col-md-4">
                        <p class="mb-1"><strong>是否确诊：</strong>{{#if (eq is_diagnosed "1")}}是{{else}}否{{/if}}</p>
                        <p class="mb-1"><strong>确诊日期：</strong>{{diagnosis_date}}</p>
                        <p class="mb-1"><strong>计划就诊：</strong>{{planned_visit_date}}</p>
                    </div>
                    <div class="col-md-4">
                        <p class="mb-1"><strong>联系人姓名：</strong>{{contact_name}}</p>
                        <p class="mb-1"><strong>监护关系：</strong>{{contact_relation}}</p>
                        <p class="mb-1"><strong>联系电话：</strong>{{contact_phone}}</p>
                    </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>常住地址：</strong></span> <span class="text-muted">{{contact_address}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>申请理由：</strong></span> <span class="text-muted">{{apply_reason}}</span> </div>
                    <div class="col-md-12">
                        <span class="mb-1"><strong>确诊报告：</strong></span>
                        <span class="d-flex flex-wrap gap-2">
                            {{#each (parseJson diagnosis_files)}}
                            <a href="{{this}}" target="_blank" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-file"></i> 查看文件
                            </a>
                            {{/each}}
                        </span>
                    </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>既往病史：</strong></span> <span class="text-muted">{{medical_history}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>过敏历史：</strong></span> <span class="text-muted">{{allergy_history}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>治疗方案：</strong></span> <span class="text-muted">{{recent_treatment}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>治疗机构：</strong></span> <span class="text-muted">{{treatment_hospital}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>康复方案：</strong></span> <span class="text-muted">{{recent_recover}}</span> </div>
                    <div class="col-md-6"> <span class="mb-1"><strong>康复机构：</strong></span> <span class="text-muted">{{recover_institution}}</span> </div>
                    {{/with}}
                </div>
            </div>
        </div>
        {{/if}}

        {{#if subject.entry_info}}
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">入组信息</h5>
                <div class="row g-3">
                    {{#with (parseJson subject.entry_info)}}
                    <div class="col-md-4">
                        <p class="mb-1"><strong>受试者姓名：</strong>{{name}}{{subject_name}}</p>
                        <p class="mb-1"><strong>性别：</strong>{{#if (eq subject_gender "1")}}男{{else}}女{{/if}}</p>
                        <p class="mb-1"><strong>出生日期：</strong>{{subject_birth_date}}</p>
                        <p class="mb-1"><strong>年龄：</strong>{{age}}</p>
                    </div>
                    <div class="col-md-4">
                        <p class="mb-1"><strong>联系人姓名：</strong>{{guardian_name}} {{recipient_name}}</p>
                        <p class="mb-1"><strong>联系人电话：</strong>{{guardian_phone}} {{recipient_phone}}</p>
                        <p class="mb-1"><strong>与受试人关系：</strong>{{guardian_relation}}</p>
                    </div>
                    <div class="col-md-4">
                        <p class="mb-1"><strong>收件地址：</strong></p>
                        <p class="text-muted mb-1">{{shipping_address.province}}{{shipping_address.detail}} {{recipient_address}}</p>
                    </div>
                    <div class="col-md-4">
                        <p class="mb-1"><strong>ADOS评分：</strong>{{ados_score}}</p>
                        <p class="mb-1"><strong>ABC评分：</strong>{{abc_score}}</p>
                        <p class="mb-1"><strong>CARS评分：</strong>{{cars_score}}</p>
                        <p class="mb-1"><strong>GSRS评分：</strong>{{gsrs_score}}</p>
                    </div>
                    <div class="col-12">
                        <p class="mb-1"><strong>入组通知书：</strong></p>
                        <div class="d-flex flex-wrap gap-2">
                            {{#each (parseJson consent_files)}}
                            <a href="{{this}}" target="_blank" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-file"></i> 查看文件
                            </a>
                            {{/each}}
                        </div>
                    </div>
                    <div class="col-12">
                        <p class="mb-1"><strong>ADOS/ABC/CARS/GSRS量表文件：</strong></p>
                        <div class="d-flex flex-wrap gap-2">
                            {{#each (parseJson scale_files)}}
                            <a href="{{this}}" target="_blank" class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-file"></i> 查看文件
                            </a>
                            {{/each}}
                        </div>
                    </div>
                    <div class="col-12">
                        <p class="mb-1"><strong>知情同意确认：</strong></p>
                        <ul class="list-unstyled text-muted small">
                            <li>
                                <i class="fas {{#if consent_check1}}fa-check text-success{{else}}fa-times text-danger{{/if}} me-1"></i>
                                已了解本试验的目的方法和可能的风险收益
                            </li>
                            <li>
                                <i class="fas {{#if consent_check2}}fa-check text-success{{else}}fa-times text-danger{{/if}} me-1"></i>
                                同意参与本试验并遵从相关自动退组的约定
                            </li>
                            <li>
                                <i class="fas {{#if consent_check3}}fa-check text-success{{else}}fa-times text-danger{{/if}} me-1"></i>
                                同意收集和使用提供的信息用于本试验研究
                            </li>
                            <li>
                                <i class="fas {{#if consent_check4}}fa-check text-success{{else}}fa-times text-danger{{/if}} me-1"></i>
                                同意在某些条件下以运费到付的方式接收试验用品
                            </li>
                        </ul>
                    </div>
                    {{/with}}
                </div>
            </div>
        </div>
        {{/if}}

        {{#if subject.group_info}}
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="alert-heading mb-2">分组信息</h6>
                <div class="row g-3">
                    <div class="col-md-4">
                        <p class="mb-1"><strong>入组编号：</strong>{{subject.group_no}}</p>
                        <p class="mb-1"><strong>分组类型：</strong>{{subject.group_type_text}}</p>
                        <p class="mb-1"><strong>分组时间：</strong>{{formatDate subject.group_time "YYYY-MM-DD HH:mm:ss"}}</p>
                    </div>
                    <div class="col-md-8">
                        {{#if subject.group_note}}
                        <p class="mb-1"><strong>分组备注：</strong></p>
                        <p class="mb-0 text-muted">{{subject.group_note}}</p>
                        {{/if}}
                    </div>
                </div>
                {{#if subject.group_info}}
                <hr>
                <h6 class="mb-2">分组提示</h6>
                <div class="group-info">
                    {{{subject.group_info}}}
                </div>
                {{/if}}
            </div>
        </div>
        {{/if}}

        {{#if (eq subject.status 3)}}
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">参试日志</h5>
                <div class="text-center">
                    <a href="/apps/trial/diary/list/{{trial.id}}?subject_id={{subject.id}}"
                       class="btn btn-primary"
                       target="_blank">
                        <i class="fas fa-book me-1"></i>查看日记记录
                    </a>
                </div>
            </div>
        </div>

        <!-- 随访报告卡片 -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">随访报告</h5>
                <div class="text-center">
                    <button class="btn btn-primary" id="viewFollowupBtn" data-subject-id="{{subject.id}}" data-trial-id="{{trial.id}}">
                        <i class="fas fa-clipboard-check me-1"></i>查看随访报告
                    </button>
                </div>
            </div>
        </div>
        {{/if}}

        <!-- 补给信息管理 -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">补给信息管理</h5>

                {{#if supplyInfo.supplies}}
                <!-- 显示补给记录列表 -->
                <div class="table-responsive mb-3">
                    <table class="table table-bordered table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>物资名称</th>
                                <th>数量</th>
                                <th>状态</th>
                                <th>物流信息</th>
                                <th>收件人</th>
                                <th>更新时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {{#each supplyInfo.supplies}}
                            <tr>
                                <td>
                                    {{#each items}}
                                    <div>{{name}}</div>
                                    {{/each}}
                                </td>
                                <td>{{#each items}}{{quantity}}{{unit}}{{/each}}</td>
                                <td>
                                    <span class="badge {{#if (eq status.code 'pending')}}bg-warning
                                        {{else if (eq status.code 'shipped')}}bg-info
                                        {{else if (eq status.code 'delivered')}}bg-success
                                        {{else}}bg-secondary{{/if}}">
                                        {{#if (eq status.code "pending")}}待发货{{/if}}
                                        {{#if (eq status.code "shipped")}}已发货{{/if}}
                                        {{#if (eq status.code "delivered")}}已送达{{/if}}
                                    </span>
                                </td>
                                <td>
                                    {{#if express_id}}
                                    <div>{{carrier}} {{express_id}}</div>
                                    {{else}}
                                    <div class="text-muted">未填写</div>
                                    {{/if}}
                                </td>
                                <td>
                                    <div>{{receiver.name}} {{receiver.phone}}</div>
                                    <small class="text-muted">{{receiver.address}}</small>
                                </td>
                                <td>{{status.timestamp}}</td>
                                <td>
                                    <button type="button" class="btn btn-sm btn-outline-primary"
                                            onclick="editSupply({{@index}})">
                                        编辑
                                    </button>
                                </td>
                            </tr>
                            {{/each}}
                        </tbody>
                    </table>
                </div>
                {{else}}
                <div class="alert alert-info">
                    该受试者尚未设置补给信息
                </div>
                {{/if}}

                <div class="text-center">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#updateSupplyModal" onclick="addNewSupply()">
                        <i class="fas fa-plus me-1"></i>添加补给记录
                    </button>
                </div>
            </div>
        </div>

        <!-- 备注档案卡片 -->
        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">备注档案</h5>
                <div class="mb-3 text-end">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#profileModal">
                        <i class="fas fa-plus me-1"></i>添加备注
                    </button>
                </div>

                <div id="profiles-list">
                    <div class="d-flex justify-content-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- 等待分组须知模态框 -->
    <div class="modal fade" id="confirmTipModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">等待分组须知</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    {{{trial.confirm_tip}}}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">我已了解</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 分组对话框 -->
    <div class="modal fade" id="groupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">设置分组 ({{subject.user_id}}-{{subject.id}})</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="groupForm">
                        <input type="hidden" name="subjectId" value="{{subject.id}}">
                        <div class="mb-3">
                            <label class="form-label">分组类型</label>
                            <select class="form-select" name="groupType" id="group-type" onchange="updateGroupInfo(this.value)">
                                <option value="0">未分组</option>
                                <!-- 分组选项将在这里动态生成 -->
                            </select>
                        </div>
                        <!-- 分组信息显示区域 -->
                        <div id="group-info-container" class="mb-3">
                            <!-- 分组信息将在这里动态显示 -->
                        </div>
                        <div class="mb-3">
                            <label class="form-label">入组编号</label>
                            <input type="text" class="form-control" name="groupNo" value="{{subject.group_no}}">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" name="groupNote" rows="3">{{subject.group_note}}</textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitGroup()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 退出试验模态框 -->
    <div class="modal fade" id="exitModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="exitForm">
                    <div class="modal-header">
                        <h5 class="modal-title">退出试验</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">退出原因</label>
                            <select class="form-select" name="exitReason" required>
                                <option value="">请选择退出原因</option>
                                <option value="adverse_event">出现不良反应</option>
                                <option value="personal">个人原因</option>
                                <option value="protocol_violation">违反试验方案</option>
                                <option value="lost_followup">失访</option>
                                <option value="other">其他原因</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">详细说明</label>
                            <textarea class="form-control" name="exitDescription" rows="3" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" onclick="submitExit()">确认退出</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 完成试验模态框 -->
    <div class="modal fade" id="finishModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="finishForm">
                    <div class="modal-header">
                        <h5 class="modal-title">完成试验</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">完成总结</label>
                            <textarea class="form-control" name="finishSummary" rows="3" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">效果评价</label>
                            <select class="form-select" name="effectiveness" required>
                                <option value="">请选择效果评价</option>
                                <option value="excellent">显著改善</option>
                                <option value="good">有所改善</option>
                                <option value="fair">略有改善</option>
                                <option value="poor">无明显改善</option>
                                <option value="tbd">尚无结论</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-success" onclick="submitFinish()">确认完成</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 更新补给信息模态框 -->
    <div class="modal fade" id="updateSupplyModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="supplyModalTitle">更新补给信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="updateSupplyForm">
                        <input type="hidden" name="supplyIndex" id="supplyIndex" value="-1">
                        <div class="mb-3">
                            <label class="form-label">物资名称</label>
                            <input type="text" class="form-control" name="productName" id="productName" placeholder="例如：图腾益星">
                        </div>
                        <div class="mb-3 row">
                            <div class="col-8">
                                <label class="form-label">数量</label>
                                <input type="number" class="form-control" name="quantity" id="quantity" value="60" min="1">
                            </div>
                            <div class="col-4">
                                <label class="form-label">单位</label>
                                <input type="text" class="form-control" name="unit" id="unit" value="条">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">物流单号</label>
                            <input type="text" class="form-control" name="trackingNumber" id="trackingNumber" placeholder="例如：SF1234567890">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">物流公司</label>
                            <input type="text" class="form-control" name="trackingCompany" id="trackingCompany" placeholder="例如：顺丰速运">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">状态</label>
                            <select class="form-select" name="status" id="status">
                                <option value="pending">待发货</option>
                                <option value="shipped">已发货</option>
                                <option value="delivered">已送达</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">收件人</label>
                            <input type="text" class="form-control" name="recipientName" id="recipientName" placeholder="收件人姓名">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">联系电话</label>
                            <input type="text" class="form-control" name="recipientPhone" id="recipientPhone" placeholder="收件人电话">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">收货地址</label>
                            <textarea class="form-control" name="recipientAddress" id="recipientAddress" rows="2" placeholder="详细收货地址"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveSupply()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 取消报名模态框 -->
    <div class="modal fade" id="cancelModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form id="cancelForm">
                    <div class="modal-header">
                        <h5 class="modal-title">取消报名</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">取消原因</label>
                            <select class="form-select" name="cancelReason" required>
                                <option value="">请选择取消原因</option>
                                <option value="admin_cancel">管理员取消</option>
                                <option value="personal">个人原因</option>
                                <option value="not_suitable">不符合试验条件</option>
                                <option value="duplicate">重复报名</option>
                                <option value="other">其他原因</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">详细说明</label>
                            <textarea class="form-control" name="cancelDescription" rows="3" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" onclick="submitCancel()">确认取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 备注档案模态框 -->
    <div class="modal fade" id="profileModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">备注档案</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="profileForm" enctype="multipart/form-data">
                        <input type="hidden" name="attachmentUrls" id="profile-attachment-urls">

                        <div class="mb-3">
                            <label class="form-label">备注内容</label>
                            <textarea class="form-control" name="content" rows="4" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">保密级别</label>
                            <select class="form-select" name="secretLevel">
                                <option value="Unclassified">普通档案</option>
                                <option value="Confidential" selected>内部档案（默认）</option>
                                <option value="Secret">机密档案</option>
                                <option value="TopSecret">绝密档案</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">附件截图</label>
                            <div class="input-group mb-3">
                                <input type="file" class="form-control" id="profile-file-upload" accept="image/*" multiple>
                                <button class="btn btn-outline-secondary" type="button" id="upload-btn">上传</button>
                            </div>
                            <div class="form-text">支持多个JPG、PNG格式的图片</div>
                            <div id="upload-preview" class="mt-2 d-flex flex-wrap gap-2"></div>
                        </div>
                    </form>

                    <div id="profile-history" class="mt-4">
                        <h6>历史备注</h6>
                        <div id="profile-history-content">
                            <!-- 历史备注将在这里显示 -->
                            <div class="d-flex justify-content-center">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="submitProfile()">保存备注</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 补给信息模态框 -->
    <div class="modal fade" id="supplyModal" tabindex="-1" aria-labelledby="supplyModalLabel" aria-hidden="true">
        // ... existing modal code ...
    </div>

    <!-- 随访报告模态框 -->
    <div class="modal fade" id="followupModal" tabindex="-1" aria-labelledby="followupModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="followupModalLabel">随访报告记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="followupList" class="mb-4">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 随访报告详情模态框 -->
    <div class="modal fade" id="followupDetailModal" tabindex="-1" aria-labelledby="followupDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="followupDetailModalLabel">随访报告详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="followupDetailContent"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 将所有JS文件移到这里，并添加defer属性 -->
    <script src="/apps/js/jquery.min.js" defer></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
    <script src="/apps/js/wx-client-dom.js" defer></script>
    <script src="/apps/js/open-oss-img-in-modal.js" defer></script>

    <script>
        // 全局变量存储试验配置
        let trialGroupConfigs = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            fetchTrialConfig();

            // 监听分组模态框显示事件
            $('#groupModal').on('show.bs.modal', function (e) {
                initGroupModal();
            });

            // 加载档案列表
            loadProfilesForList();
        });

        // 获取试验配置
        async function fetchTrialConfig() {
            try {
                const response = await fetch(`/apps/trial/admin/trials/{{subject.trial_id}}`);
                const data = await response.json();

                if (data.trial && data.trial.group_config) {
                    try {
                        trialGroupConfigs = JSON.parse(data.trial.group_config);
                    } catch (e) {
                        console.error('解析分组配置失败:', e);
                        trialGroupConfigs = [];
                    }
                }
            } catch (error) {
                console.error('获取试验信息失败:', error);
            }
        }

        // 初始化分组模态框
        function initGroupModal() {
            // 更新分组选项
            updateGroupOptions();

            // 如果已有分组，选中对应的选项
            const currentGroupType = "{{subject.group_type}}";
            if (currentGroupType) {
                document.getElementById('group-type').value = currentGroupType;
                updateGroupInfo(currentGroupType);
            }
        }

        // 更新分组选项
        function updateGroupOptions() {
            const groupTypeSelect = document.getElementById('group-type');

            // 清除除了"未分组"选项外的所有选项
            while (groupTypeSelect.options.length > 1) {
                groupTypeSelect.remove(1);
            }

            // 根据分组配置添加选项
            if (trialGroupConfigs && trialGroupConfigs.length > 0) {
                trialGroupConfigs.forEach(config => {
                    const option = document.createElement('option');
                    option.value = config.group_type;
                    option.textContent = config.group_name;
                    groupTypeSelect.appendChild(option);
                });
            } else {
                // 如果没有配置，添加默认选项
                const options = [
                    { value: 1, text: '试验组' },
                    { value: 2, text: '对照组' },
                    { value: 9, text: '观察组' }
                ];

                options.forEach(opt => {
                    const option = document.createElement('option');
                    option.value = opt.value;
                    option.textContent = opt.text;
                    groupTypeSelect.appendChild(option);
                });
            }
        }

        // 更新分组信息显示
        function updateGroupInfo(groupType) {
            // 查找所选分组的配置
            const selectedGroup = trialGroupConfigs.find(config => config.group_type == groupType);

            // 更新分组信息显示
            const groupInfoContainer = document.getElementById('group-info-container');
            if (groupInfoContainer) {
                if (selectedGroup) {
                    groupInfoContainer.innerHTML = `
                        <div class="alert alert-info">
                            <h5>${selectedGroup.group_name}</h5>
                            <p><strong>随访天数:</strong> ${selectedGroup.duration}天</p>
                            <p><strong>每日打卡:</strong> ${selectedGroup.daily_diary ? '是' : '否'}</p>
                            <p><strong>随访日期:</strong> ${selectedGroup.follow_up_dates.join(', ')}</p>
                        </div>
                    `;
                } else {
                    groupInfoContainer.innerHTML = '';
                }
            }
        }

        // 提交分组设置
        function submitGroup() {
            const form = document.getElementById('groupForm');
            const subjectId = form.subjectId.value;
            const groupNo = form.groupNo.value;
            const groupType = form.groupType.value;
            const groupNote = form.groupNote.value;

            if (!groupNo || !groupType) {
                alert('请填写完整信息');
                return;
            }

            // 显示加载状态
            const submitBtn = document.querySelector('#groupModal .btn-primary');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 处理中...';

            fetch(`/apps/trial/subjects/${subjectId}/group`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    groupNo,
                    groupType,
                    groupNote
                })
            })
            .then(response => {
                // 检查响应状态
                if (!response.ok) {
                    if (response.status === 401 || response.status === 403) {
                        throw new Error('会话已过期，请重新登录');
                    }
                    throw new Error(`服务器返回错误: ${response.status}`);
                }

                // 检查内容类型
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('服务器返回了非JSON格式的响应，可能需要重新登录');
                }

                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('分组设置成功');
                    location.reload();
                } else {
                    alert('分组设置失败: ' + (data.message || '未知原因'));
                }
            })
            .catch(error => {
                console.error('分组设置错误:', error);

                // 针对会话过期的特殊处理
                if (error.message.includes('会话已过期') || error.message.includes('非JSON格式')) {
                    alert('您的登录会话可能已过期，请刷新页面后重试');
                } else {
                    alert('设置分组失败: ' + error.message);
                }
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        }

        // 提交退出试验
        function submitExit() {
            const form = document.getElementById('exitForm');
            const reason = form.exitReason.value;
            const description = form.exitDescription.value;

            if (!reason || !description) {
                alert('请填写完整信息');
                return;
            }

            fetch(`/apps/trial/subjects/{{subject.id}}/exit`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    reason,
                    description
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('退出试验操作成功');
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        }

        // 提交完成试验
        function submitFinish() {
            const form = document.getElementById('finishForm');
            const summary = form.finishSummary.value;
            const effectiveness = form.effectiveness.value;

            if (!summary || !effectiveness) {
                alert('请填写完整信息');
                return;
            }

            fetch(`/apps/trial/subjects/{{subject.id}}/finish`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    summary,
                    effectiveness
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('完成试验操作成功');
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        }

        // 添加新补给记录
        function addNewSupply() {
            document.getElementById('supplyModalTitle').textContent = '添加补给记录';
            document.getElementById('supplyIndex').value = '-1';

            // 重置表单
            document.getElementById('productName').value = '图腾益星试验用';
            document.getElementById('quantity').value = '60';
            document.getElementById('unit').value = '条';
            document.getElementById('trackingNumber').value = '';
            document.getElementById('trackingCompany').value = '';
            document.getElementById('status').value = 'pending';
            document.getElementById('recipientName').value = '';
            document.getElementById('recipientPhone').value = '';
            document.getElementById('recipientAddress').value = '';

            // 尝试从现有记录或entry_info中获取收件人信息
            fetchReceiverInfo();
        }

        // 编辑现有补给记录
        function editSupply(index) {
            document.getElementById('supplyModalTitle').textContent = '编辑补给记录';
            document.getElementById('supplyIndex').value = index;

            // 获取当前的补给信息
            fetch(`/apps/trial/subjects/{{subject.id}}/supply-info`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.supplies && data.supplies[index]) {
                    const supply = data.supplies[index];

                    // 填充表单
                    if (supply.items && supply.items.length > 0) {
                        document.getElementById('productName').value = supply.items[0].name || '';
                        document.getElementById('quantity').value = supply.items[0].quantity || '60';
                        document.getElementById('unit').value = supply.items[0].unit || '条';
                    }

                    document.getElementById('trackingNumber').value = supply.express_id || '';
                    document.getElementById('trackingCompany').value = supply.carrier || '';
                    document.getElementById('status').value = supply.status?.code || 'pending';

                    if (supply.receiver) {
                        document.getElementById('recipientName').value = supply.receiver.name || '';
                        document.getElementById('recipientPhone').value = supply.receiver.phone || '';
                        document.getElementById('recipientAddress').value = supply.receiver.address || '';
                    }

                    // 显示模态框
                    const updateSupplyModal = new bootstrap.Modal(document.getElementById('updateSupplyModal'));
                    updateSupplyModal.show();
                } else {
                    alert('获取补给信息失败，请重试');
                }
            })
            .catch(error => {
                console.error('获取供应信息失败:', error);
                alert('获取供应信息失败，请重试');
            });
        }

        // 获取收件人信息
        function fetchReceiverInfo() {
            fetch(`/apps/trial/subjects/{{subject.id}}/receiver-info`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.receiver) {
                    document.getElementById('recipientName').value = data.receiver.name || '';
                    document.getElementById('recipientPhone').value = data.receiver.phone || '';
                    document.getElementById('recipientAddress').value = data.receiver.address || '';
                }
            })
            .catch(error => {
                console.error('获取收件人信息失败:', error);
            });
        }

        // 保存补给信息
        function saveSupply() {
            const form = document.getElementById('updateSupplyForm');
            const index = parseInt(form.supplyIndex.value);
            const productName = form.productName.value;
            const quantity = form.quantity.value;
            const unit = form.unit.value;
            const trackingNumber = form.trackingNumber.value;
            const trackingCompany = form.trackingCompany.value;
            const status = form.status.value;
            const recipientName = form.recipientName.value;
            const recipientPhone = form.recipientPhone.value;
            const recipientAddress = form.recipientAddress.value;

            if (!productName || !quantity || !unit) {
                alert('请填写完整的物资信息');
                return;
            }

            if (!recipientName || !recipientPhone || !recipientAddress) {
                alert('请填写完整的收件人信息');
                return;
            }

            // 显示加载状态
            const submitBtn = document.querySelector('#updateSupplyModal .btn-primary');
            const originalText = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...';

            // 构建补给记录对象
            const supplyData = {
                index: index,
                supply: {
                    express_id: trackingNumber,
                    carrier: trackingCompany,
                    status: {
                        code: status,
                        timestamp: new Date().toISOString().slice(0, 19).replace('T', ' ')
                    },
                    receiver: {
                        name: recipientName,
                        phone: recipientPhone,
                        address: recipientAddress
                    },
                    items: [
                        {
                            name: productName,
                            quantity: parseInt(quantity),
                            unit: unit
                        }
                    ]
                }
            };

            // 判断是新增还是编辑
            let url = `/apps/trial/subjects/{{subject.id}}/update-supply`;
            let method = 'POST';

            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(supplyData)
            })
            .then(response => {
                if (!response.ok) {
                    if (response.status === 401 || response.status === 403) {
                        throw new Error('会话已过期，请重新登录');
                    }
                    throw new Error(`服务器返回错误: ${response.status}`);
                }

                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('服务器返回了非JSON格式的响应，可能需要重新登录');
                }

                return response.json();
            })
            .then(result => {
                if (result.success) {
                    alert('补给信息保存成功');
                    location.reload();
                } else {
                    alert('保存失败: ' + (result.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('保存补给信息失败:', error);

                if (error.message.includes('会话已过期') || error.message.includes('非JSON格式')) {
                    alert('您的登录会话可能已过期，请刷新页面后重试');
                } else {
                    alert('保存失败: ' + error.message);
                }
            })
            .finally(() => {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            });
        }

        // 更新补给信息 (旧方法，保留用于兼容)
        function updateSupply() {
            // 调用新的保存方法
            saveSupply();
        }

        // 更新状态
        function updateStatus(subjectId) {
            fetch(`/apps/trial/subjects/${subjectId}/update-status`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('状态更新成功');
                    location.reload();
                } else {
                    alert('状态更新失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        }

        // 提交取消报名
        function submitCancel() {
            const form = document.getElementById('cancelForm');
            const reason = form.cancelReason.value;
            const description = form.cancelDescription.value;

            if (!reason || !description) {
                alert('请填写完整信息');
                return;
            }

            fetch(`/apps/trial/subjects/{{subject.id}}/cancel`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    reason,
                    description
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('取消报名操作成功');
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败，请重试');
            });
        }

        // 加载历史备注
        function loadProfileHistory() {
            fetch(`/apps/trial/subjects/{{subject.id}}/profiles?trial_id={{trial.id}}`)
            .then(response => response.json())
            .then(result => {
                const historyContent = document.getElementById('profile-history-content');

                if (result.success) {
                    if (result.profiles.length === 0) {
                        historyContent.innerHTML = '<div class="alert alert-info">暂无历史备注</div>';
                        return;
                    }

                    let html = '<div class="list-group">';
                    result.profiles.forEach(profile => {
                        // 根据confidentiality字段获取对应的显示名称和样式
                        let secretLevelText = '普通档案';
                        let badgeClass = 'bg-secondary';

                        switch (profile.confidentiality) {
                            case 'TopSecret':
                                secretLevelText = '绝密档案';
                                badgeClass = 'bg-danger';
                                break;
                            case 'Secret':
                                secretLevelText = '机密档案';
                                badgeClass = 'bg-warning text-dark';
                                break;
                            case 'Confidential':
                                secretLevelText = '内部档案';
                                badgeClass = 'bg-info text-dark';
                                break;
                            case 'Unclassified':
                            default:
                                secretLevelText = '普通档案';
                                badgeClass = 'bg-secondary';
                                break;
                        }

                        let attachmentsHtml = '';
                        if (profile.attachment_urls ) {
                            attachmentsHtml = '<div class="d-flex flex-wrap gap-2 mt-2">';
                            const urls = JSON.parse(profile.attachment_urls);
                            urls.forEach(url => {
                                attachmentsHtml += `<a href="javascript:showImageModal('${url}')" class="me-2">
                                    <img src="${url}" alt="附件" class="img-thumbnail" style="width: 80px; height: 80px; object-fit: cover;">
                                </a>`;
                            });
                            attachmentsHtml += '</div>';
                        }

                        // 使用add_time转换为本地日期
                        const createdAt = new Date(profile.add_time * 1000).toLocaleString();

                        html += `
                        <div class="list-group-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">${createdAt} · ${profile.operator_name || '系统'} · <span class="badge ${badgeClass}">${secretLevelText}</span></small>
                            </div>
                            <p class="mb-1 mt-2">${profile.content}</p>
                            ${attachmentsHtml}
                        </div>`;
                    });
                    html += '</div>';

                    historyContent.innerHTML = html;
                } else {
                    historyContent.innerHTML = `<div class="alert alert-danger">${result.message || '加载备注历史失败'}</div>`;
                }
            })
            .catch(error => {
                console.error('加载备注历史失败:', error);
                document.getElementById('profile-history-content').innerHTML =
                    '<div class="alert alert-danger">加载备注历史失败，请重试</div>';
            });
        }

        // 提交备注档案
        function submitProfile() {
            const form = document.getElementById('profileForm');
            const content = form.querySelector('[name="content"]').value;
            const confidentiality = form.querySelector('[name="secretLevel"]').value;
            const attachmentUrls = document.getElementById('profile-attachment-urls').value;

            if (!content) {
                alert('请填写备注内容');
                return;
            }

            fetch(`/apps/trial/subjects/{{subject.id}}/profile`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    trialId: '{{trial.id}}',
                    userId: '{{subject.user_id}}',
                    content,
                    confidentiality,
                    attachmentUrls: attachmentUrls ? JSON.parse(attachmentUrls) : []
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('备注档案保存成功');
                    loadProfileHistory();
                    form.reset();
                    document.getElementById('upload-preview').innerHTML = '';
                    document.getElementById('profile-attachment-urls').value = '';

                    // 刷新档案列表
                    loadProfilesForList();
                } else {
                    alert(result.message || '保存备注档案失败');
                }
            })
            .catch(error => {
                console.error('保存备注档案失败:', error);
                alert('保存备注档案失败，请重试');
            });
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 如果有备注档案模态框，则加载历史备注
            if (document.getElementById('profileModal')) {
                const profileModal = document.getElementById('profileModal');
                profileModal.addEventListener('show.bs.modal', function () {
                    loadProfileHistory();
                    // 清空上传预览和隐藏字段
                    document.getElementById('upload-preview').innerHTML = '';
                    document.getElementById('profile-attachment-urls').value = '';
                });

                // 初始化文件上传按钮
                const uploadBtn = document.getElementById('upload-btn');
                if (uploadBtn) {
                    uploadBtn.addEventListener('click', uploadAttachments);
                }
            }

            // 加载档案列表
            loadProfilesForList();

            // 初始化分组模态框
            const groupModal = document.getElementById('groupModal');
            if (groupModal) {
                groupModal.addEventListener('show.bs.modal', function () {
                    initGroupModal();
                });
            }
        });

        // 加载备注档案到列表
        function loadProfilesForList() {
            const profilesList = document.getElementById('profiles-list');
            if (!profilesList) return;

            fetch(`/apps/trial/subjects/{{subject.id}}/profiles?trial_id={{trial.id}}`)
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    if (result.profiles.length === 0) {
                        profilesList.innerHTML = '<div class="alert alert-info">暂无备注档案</div>';
                        return;
                    }

                    let html = '';
                    result.profiles.forEach(profile => {
                        // 根据confidentiality字段获取对应的显示名称和样式
                        let secretLevelText = '普通档案';
                        let badgeClass = 'bg-secondary';

                        switch (profile.confidentiality) {
                            case 'TopSecret':
                                secretLevelText = '绝密档案';
                                badgeClass = 'bg-danger';
                                break;
                            case 'Secret':
                                secretLevelText = '机密档案';
                                badgeClass = 'bg-warning text-dark';
                                break;
                            case 'Confidential':
                                secretLevelText = '内部档案';
                                badgeClass = 'bg-info text-dark';
                                break;
                            case 'Unclassified':
                            default:
                                secretLevelText = '普通档案';
                                badgeClass = 'bg-secondary';
                                break;
                        }

                        // 使用add_time转换为本地日期
                        const date = new Date(profile.add_time * 1000).toLocaleString();

                        let attachmentsHtml = '';
                        if (profile.attachment_urls ) {
                            attachmentsHtml = '<div class="d-flex flex-wrap gap-2 mt-2">';
                            const urls = JSON.parse(profile.attachment_urls);
                            urls.forEach( url => {
                                attachmentsHtml += `<a href="javascript:showImageModal('${url}')" class="me-2">
                                    <img src="${url}" alt="附件" class="img-thumbnail" style="width: 80px; height: 80px; object-fit: cover;">
                                </a>`;
                            });
                            attachmentsHtml += '</div>';
                        }

                        html += `
                        <div class="card mb-3 border-0 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <h6 class="card-subtitle mb-2 text-muted">
                                        ${date} · ${profile.operator_name || '系统'}
                                        <span class="badge ${badgeClass}">${secretLevelText}</span>
                                    </h6>
                                </div>
                                <p class="card-text">${profile.content}</p>
                                ${attachmentsHtml}
                            </div>
                        </div>`;
                    });

                    profilesList.innerHTML = html;
                } else {
                    profilesList.innerHTML = `<div class="alert alert-danger">${result.message || '加载备注档案失败'}</div>`;
                }
            })
            .catch(error => {
                console.error('加载备注档案失败:', error);
                profilesList.innerHTML = '<div class="alert alert-danger">加载备注档案失败，请重试</div>';
            });
        }

        // 上传附件
        async function uploadAttachments() {
            const fileInput = document.getElementById('profile-file-upload');
            const files = fileInput.files;
            const uploadBtn = document.getElementById('upload-btn');

            if (!files || files.length === 0) {
                alert('请选择要上传的文件');
                return;
            }

            const uploadPreview = document.getElementById('upload-preview');
            const attachmentUrlsInput = document.getElementById('profile-attachment-urls');

            // 显示上传中状态
            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 上传中...';

            try {
                const uploadPromises = [];
                const uploadedUrls = [];

                // 如果已有上传文件，获取现有URL
                let existingUrls = [];
                if (attachmentUrlsInput.value) {
                    try {
                        existingUrls = JSON.parse(attachmentUrlsInput.value);
                    } catch (e) {
                        existingUrls = [];
                    }
                }

                // 上传每个文件
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const formData = new FormData();
                    formData.append('file', file);

                    const uploadPromise = fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.data && result.data.src) {
                            uploadedUrls.push(result.data.src);

                            // 创建预览
                            const previewItem = document.createElement('div');
                            previewItem.className = 'position-relative';
                            previewItem.innerHTML = `
                                <img src="${result.data.src}" class="img-thumbnail" style="width: 100px; height: 100px; object-fit: cover;">
                                <button type="button" class="btn-close position-absolute top-0 end-0 bg-danger"
                                        style="font-size: 0.7rem;" data-url="${result.url}"></button>
                            `;

                            // 添加删除功能
                            const closeBtn = previewItem.querySelector('.btn-close');
                            closeBtn.addEventListener('click', function() {
                                const url = this.getAttribute('data-url');
                                removeAttachment(url);
                                previewItem.remove();
                            });

                            uploadPreview.appendChild(previewItem);
                            return result.url;
                        } else {
                            throw new Error(result.message || '上传失败');
                        }
                    });

                    uploadPromises.push(uploadPromise);
                }

                const results = await Promise.all(uploadPromises);

                // 合并新上传的URL和现有的URL
                const allUrls = [...existingUrls, ...uploadedUrls];

                // 更新隐藏字段
                attachmentUrlsInput.value = JSON.stringify(allUrls);

                // 重置文件输入
                fileInput.value = '';

            } catch (error) {
                console.error('上传文件失败:', error);
                alert('上传文件失败: ' + error.message);
            } finally {
                // 恢复上传按钮状态
                uploadBtn.disabled = false;
                uploadBtn.innerHTML = '上传';
            }
        }

        // 移除附件
        function removeAttachment(url) {
            const attachmentUrlsInput = document.getElementById('profile-attachment-urls');
            let urls = [];

            try {
                urls = JSON.parse(attachmentUrlsInput.value);
            } catch (e) {
                urls = [];
            }

            // 从URL数组中移除指定URL
            const updatedUrls = urls.filter(item => item !== url);

            // 更新隐藏字段
            attachmentUrlsInput.value = JSON.stringify(updatedUrls);
        }

        // 加载随访报告列表
        document.getElementById('viewFollowupBtn')?.addEventListener('click', function() {
            const subjectId = this.getAttribute('data-subject-id');
            const trialId = this.getAttribute('data-trial-id');
            loadFollowupReports(subjectId, trialId);
            const followupModal = new bootstrap.Modal(document.getElementById('followupModal'));
            followupModal.show();
        });

        // 加载随访报告
        async function loadFollowupReports(subjectId, trialId) {
            try {
                // 显示加载状态
                document.getElementById('followupList').innerHTML = `
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                `;

                // 显示请求参数
                console.log(`正在请求随访报告: subjectId=${subjectId}, trialId=${trialId}`);

                // 调用API获取随访报告
                const response = await fetch(`/apps/trial/subjects/${subjectId}/follow-ups?trial_id=${trialId}`);

                // 检查响应状态
                if (!response.ok) {
                    const text = await response.text();
                    console.error(`API返回错误 (${response.status}): ${text}`);
                    throw new Error(`服务器返回错误 (${response.status}): ${response.statusText}`);
                }

                // 尝试解析JSON
                let data;
                try {
                    const text = await response.text();
                    console.log('API返回的原始内容:', text.substring(0, 200) + '...');
                    data = JSON.parse(text);
                } catch (parseError) {
                    console.error('解析JSON失败:', parseError);
                    throw new Error(`解析响应数据失败: ${parseError.message}`);
                }

                if (!data.success) {
                    throw new Error(data.message || '获取随访报告失败');
                }

                console.log(`成功获取随访报告: ${data.followups.length}条记录`);
                updateFollowupList(data.followups, data.startDate);
            } catch (error) {
                console.error('加载随访报告失败:', error);
                document.getElementById('followupList').innerHTML = `
                    <div class="alert alert-danger">
                        加载随访报告失败：${error.message}
                        <div class="mt-2">
                            <small class="text-muted">请联系管理员检查API配置，或查看控制台了解详细错误信息</small>
                        </div>
                    </div>
                `;
            }
        }

        // 更新随访报告列表
        function updateFollowupList(followups, startDate) {
            const followupList = document.getElementById('followupList');
            followupList.innerHTML = '';

            // 如果没有随访记录，显示提示信息
            if (!followups || followups.length === 0) {
                followupList.innerHTML = '<div class="alert alert-info">暂无随访报告记录</div>';
                return;
            }

            // 创建已完成随访列表
            const completedList = document.createElement('div');
            completedList.className = 'list-group mb-4';

            // 排序：按targetDay降序排列
            followups.sort((a, b) => b.targetDay - a.targetDay);

            // 添加每条随访记录
            followups.forEach(followup => {
                const targetDate = followup.targetDate ? new Date(followup.targetDate) : null;
                const formattedTargetDate = targetDate ? formatDate(targetDate) : '未知';

                const actualDate = followup.date ? new Date(followup.date) : new Date(followup.createdAt);
                const formattedActualDate = formatDate(actualDate);

                const content = followup.content || {};

                // 创建列表项
                const item = document.createElement('div');
                item.className = 'list-group-item';
                item.innerHTML = `
                    <div class="d-flex w-100 justify-content-between">
                        <h5 class="mb-1">第 ${followup.targetDay} 天随访报告</h5>
                        <small class="text-muted">完成于 ${formattedActualDate}</small>
                    </div>
                    <p class="mb-1">计划日期: ${formattedTargetDate}</p>
                    <button class="btn btn-outline-primary btn-sm mt-2 view-followup-detail-btn" data-followup='${JSON.stringify(followup)}'>
                        <i class="fas fa-eye"></i> 查看详情
                    </button>
                `;

                completedList.appendChild(item);
            });

            followupList.appendChild(completedList);

            // 添加查看详情按钮事件
            document.querySelectorAll('.view-followup-detail-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const followup = JSON.parse(this.getAttribute('data-followup'));
                    showFollowupDetail(followup);
                });
            });
        }

        // 显示随访详情
        function showFollowupDetail(followup) {
            const content = followup.content || {};
            const targetDate = followup.targetDate ? new Date(followup.targetDate) : null;
            const formattedTargetDate = targetDate ? formatDate(targetDate) : '未知';

            const actualDate = followup.date ? new Date(followup.date) : new Date(followup.createdAt);
            const formattedActualDate = formatDate(actualDate);

            const detailContent = document.getElementById('followupDetailContent');
            let html = `
                <div class="row mb-3">
                    <div class="col-md-6">
                        <strong>计划日期:</strong> ${formattedTargetDate}
                    </div>
                    <div class="col-md-6">
                        <strong>完成日期:</strong> ${formattedActualDate}
                    </div>
                </div>
            `;

            // 动态构建报告详情内容
            if (content.emotion_score) {
                html += `
                    <div class="mb-3">
                        <strong>情绪状态:</strong>
                        <p>${content.emotion_score}分</p>
                    </div>
                `;
            }

            if (content.behaviors && content.behaviors.length > 0) {
                html += `
                    <div class="mb-3">
                        <strong>行为特征:</strong>
                        <p>
                            ${content.behaviors.join('、')}
                            ${content.behavior_other && content.behaviors.includes('其它') ?
                                `（${content.behavior_other}）` : ''}
                        </p>
                    </div>
                `;
            }

            if (content.diet && content.diet.length > 0) {
                html += `
                    <div class="mb-3">
                        <strong>饮食记录:</strong>
                        <p>
                            ${content.diet.map(item => {
                                if (item === '挑食' && content.diet_picky) return `${item}（${content.diet_picky}）`;
                                if (item === '过敏' && content.diet_allergy) return `${item}（${content.diet_allergy}）`;
                                return item;
                            }).join('、')}
                        </p>
                    </div>
                `;
            }

            if (content.sleep_hours || content.sleep_interruptions) {
                html += `
                    <div class="mb-3">
                        <strong>睡眠质量:</strong>
                        <p>每日总时长: ${content.sleep_hours || '0'}小时; 中断次数: ${content.sleep_interruptions || '0'}次</p>
                    </div>
                `;
            }

            if (content.gi_symptoms) {
                html += `
                    <div class="mb-3">
                        <strong>胃肠反应:</strong>
                        <p>${content.gi_symptoms}</p>
                    </div>
                `;
            }

            if (content.illness && content.illness.length > 0) {
                html += `
                    <div class="mb-3">
                        <strong>感冒生病:</strong>
                        <p>
                            ${content.illness.map(item => {
                                if (item === '其他' && content.illness_other) return `${item}（${content.illness_other}）`;
                                if (item === '用药' && content.medication) return `${item}（${content.medication}）`;
                                return item;
                            }).join('、')}
                        </p>
                    </div>
                `;
            }

            if (content.consultation) {
                html += `
                    <div class="mb-3">
                        <strong>咨询问题:</strong>
                        <p>${content.consultation}</p>
                    </div>
                `;
            }

            // 处理其他可能存在的字段
            const knownFields = [
                'targetDay', 'emotion_score', 'behaviors', 'behavior_other',
                'diet', 'diet_picky', 'diet_allergy', 'sleep_hours',
                'sleep_interruptions', 'gi_symptoms', 'illness',
                'illness_other', 'medication', 'consultation'
            ];

            const otherFields = Object.keys(content).filter(key => !knownFields.includes(key));

            if (otherFields.length > 0) {
                html += `<div class="mb-3"><strong>其他信息:</strong><ul>`;
                otherFields.forEach(key => {
                    const value = content[key];
                    if (value && (typeof value === 'string' || typeof value === 'number')) {
                        html += `<li><strong>${key}:</strong> ${value}</li>`;
                    } else if (Array.isArray(value) && value.length > 0) {
                        html += `<li><strong>${key}:</strong> ${value.join('、')}</li>`;
                    }
                });
                html += `</ul></div>`;
            }

            detailContent.innerHTML = html;

            // 显示模态框
            const detailModal = new bootstrap.Modal(document.getElementById('followupDetailModal'));
            detailModal.show();
        }

        // 格式化日期函数
        function formatDate(date) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
        }
    </script>
</body>
</html>
